//
//  VoiceReadDetailContentCell.m
//  ShowYork
//
//  Created by hxh on 2021/4/20.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "VoiceReadDetailContentCell.h"
#import "PublicAudioPlayProgressView.h"
@interface VoiceReadDetailContentCell ()<PublicAudioPlayProgressViewDelegate>
@property (nonatomic,strong)UIView *shadowView;
@property (nonatomic,strong)UIView *containView;
@property (nonatomic,strong)UIImageView *playIcon;
@property (nonatomic,strong)UILabel *playTitleLb;
@property (nonatomic,strong)UILabel *contentLb;
@property (nonatomic,strong)PublicAudioPlayProgressView *progressView;

@property (nonatomic,strong)UIImageView *tst;



@end

@implementation VoiceReadDetailContentCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setUI];
    }
    return self;
}
- (void)setUI{
    
    
    
    
    self.shadowView             = [UIView new];
    [self.contentView addSubview:self.shadowView];
    
    self.shadowView.layer.shadowColor   = RGBA(238, 238, 238, 1).CGColor;
    self.shadowView.layer.shadowOffset  = CGSizeMake(0, 0);
    self.shadowView.layer.shadowOpacity = 0.8;
    self.shadowView.layer.shadowRadius  = 4;
    
    self.containView = [[UIView alloc]init];
    self.containView.layer.backgroundColor = [UIColor whiteColor].CGColor;
    self.containView.layer.shadowColor = RGBA(238, 238, 238, 1).CGColor;
    self.containView.layer.shadowOffset = CGSizeMake(0,0);
    self.containView.layer.shadowOpacity = 1;
    self.containView.layer.shadowRadius = 5;
    [self.shadowView addSubview:self.containView];
    
    
    
    [self.shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.containView);
    }];
    
    [self.containView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(32);
        make.left.equalTo(self.contentView).offset(16);
        make.right.equalTo(self.contentView).offset(-16);
        make.height.mas_equalTo(80).priorityHigh();
    }];
    
    self.playIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"voice_stop_tag"]];
    self.playIcon.highlightedImage = [UIImage imageNamed:@"voice_start_tag"];
    [self.containView addSubview:self.playIcon];
    [self.playIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.containView).offset(-16);
        make.centerY.equalTo(self.containView);
        make.size.mas_equalTo(self.playIcon.image.size);
    }];
    
    self.playTitleLb = [[UILabel alloc]init];
    self.playTitleLb.text = @"无用的一面，真正的问题却被遮掩起来或围不谈。自卑者限制自身的活动范围，苦心孤诣地要避免失败，而不是追求成功，在困难面前犹疑、彷徨甚至退却。获取优越感而不是改进情境。他们隐藏起来而不为人所见的，则是超越一切、好高骛远的";
    self.playTitleLb.textColor = C51;
    self.playTitleLb.font = [UIFont boldSystemFontOfSize:14];
    self.playTitleLb.lineBreakMode = NSLineBreakByClipping;
    [self.containView addSubview:self.playTitleLb];
    [self.playTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.containView).offset(16);
        make.right.equalTo(self.playIcon.mas_left).offset(-20);
        make.centerY.equalTo(self.containView);
    }];
    
    
    self.contentLb = [[UILabel alloc]init];
    self.contentLb.text = @"没有勇气改变现状，用自欺的方式麻痹自己。由于自卑感总是造成紧张，所以争取优越感的补偿动作必然会同时出现，但是其目的却不在于解决问题。争取优越感的动作总是朝向生活中无用的一面，真正的问题却被遮掩起来或摒开不谈。自卑者限制自身的活动范围，苦心孤诣地要避免失败，而不是追求成功，在困难面前犹疑、彷徨甚至退却。获取优越感而不是改进情境。他们隐藏起来而不为人所见的，则是超越一切、好高骛远的目标，和不惜任何代价以凌驾别人的决心。一个人如果不敢在外界随心所欲地应付其爱情问题，他便无法成功地解决此问题。由于他的不安全感，他从未把他的兴趣扩展至他最熟悉的少数几个人之外。他怕跟别人相处时，他就不能再依照他习惯的方式来控制局势。受的教养告诉他：自己的愿望是有天生就被实现的权利的，而他们也从不知道：他们能凭自己的努力，在家庭的范围之外，赢取温暖和爱情。在任何孩子身上，我们都可能造成奥迪普斯情结。我们所需要的，是让他的母亲宠惯他，不准他把兴趣扩展至别人身上，并要他的父亲对他冷漠而不关心。假使一个儿童未曾学会合作之道，那么他一定会走向悲观之途，并发展出牢固的自卑情结";
    self.contentLb.numberOfLines = 0;
    self.contentLb.textColor = C51;
    self.contentLb.font = font(14);
    [self.contentView addSubview:self.contentLb];
    [self.contentLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containView.mas_bottom).offset(32);
        make.left.equalTo(self.contentView).offset(16);
        make.right.equalTo(self.contentView).offset(-16);
        make.bottom.equalTo(self.contentView).offset(-48);
    }];
    
    NSMutableParagraphStyle*style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    style.lineSpacing = 12;
    NSAttributedString*attrText = [[NSAttributedString alloc] initWithString:self.contentLb.text attributes:@{NSParagraphStyleAttributeName: style}];
    self.contentLb.attributedText = attrText;
    
    self.progressView = [PublicAudioPlayProgressView publicAudioPlayProgressView:CGRectMake(16,32 + 72, kScreenW - 32,18)];
    self.progressView.delegate = self;
    self.progressView.hidden = NO;
    
    [self.progressView changePlayProgress:0 totalLength:0];
    [self.contentView addSubview:self.progressView];
   
    self.playIcon.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playOrPause)];
    [self.playIcon addGestureRecognizer:tap];


    self.tst = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"vioce_loading_tag"]];
    [self.contentView addSubview:self.tst];
    
    [self.tst mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.playIcon);
    }];
    
    self.tst.hidden = YES;
    
    
}

- (void)startAnimation{
    
    self.tst.hidden = NO;
    self.playIcon.hidden = YES;
    
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0f];
    rotationAnimation.duration = 2;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = MAXFLOAT;
    [self.tst.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
   
}
- (void)stopAnimation{
    
    [self.tst.layer removeAllAnimations];
    
    self.tst.hidden = YES;
    
    self.playIcon.hidden = NO;
}


- (void)playOrPause{
    
    NSNumber *status = [[NSUserDefaults standardUserDefaults]objectForKey:@"NetworkStatus"];
    if (![status boolValue]) {
        
        [WHToast showMessage:@"网络好像有点问题，请检查后重试" duration:2 finishHandler:nil];
        
        return;
    }
    if (self.model.status == XHPlayerFailed) {
        
//        if (self.delegate && [self.delegate respondsToSelector:@selector(failedWithCurrentModel:)]) {
//            [self.delegate failedWithCurrentModel:self.model];
//            [WHToast showMessage:@"抱歉，播放出错了" duration:2 finishHandler:nil];
//        }
//        return;
    }

    self.model.isLoading = self.model.progress == 0;
    if (self.model.isLoading && self.model.status == XHPlayerPlay) {
        [self startAnimation];
    }else{
        if (self.model.status == XHPlayerPlay) {
            self.playIcon.highlighted = NO;
            self.model.status = XHPlayerPause;
            [self stopAnimation];
            if (self.delegate && [self.delegate respondsToSelector:@selector(pauseWithCurrentModel:)]) {
                [self.delegate pauseWithCurrentModel:self.model];
            }
        }else{
            self.playIcon.highlighted = YES;
            self.model.status = XHPlayerPlay;
            [self startAnimation];
            if (self.delegate && [self.delegate respondsToSelector:@selector(playWithCurrentModel:)]) {
                [self.delegate playWithCurrentModel:self.model];
            }
        }
    }
}

+(instancetype)cellWithTableView:(UITableView *)tableView{
    NSString *ID = @"VoiceReadDetailContentCell";
    VoiceReadDetailContentCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[VoiceReadDetailContentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.containView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(8, 8)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.containView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.containView.layer.mask = maskLayer;
}
- (void) changePlayTimeByPublicAudioPlayProgressView:(int) playCount{
    if (self.delegate && [self.delegate respondsToSelector:@selector(changePlayCountByProgressView:)]) {
        [self.delegate changePlayCountByProgressView:playCount];
    }
}
- (void)changePlayEndeByPublicAudioPlayProgressView:(CGFloat)playCount{
    if (self.delegate && [self.delegate respondsToSelector:@selector(changeEndCountByProgressView:)]) {
        [self.delegate changeEndCountByProgressView:playCount];
    }
}

- (void)changePlayBeginByPublicAudioPlayProgressView:(CGFloat)playCount{
    if (self.delegate && [self.delegate respondsToSelector:@selector(changeBeginCountByProgressView:)]) {
        [self.delegate changeBeginCountByProgressView:playCount];
    }
}

- (void)setModel:(VoiceReadDetailPlayerModel *)model{
    _model = model;
        
    NSMutableParagraphStyle*style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    style.lineSpacing = 12;
//    style.firstLineHeadIndent = 28;
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithData:[model.voiceContent dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
    [attrString addAttributes:@{NSParagraphStyleAttributeName:style} range:NSMakeRange(0,attrString.length)];
//    [attrString addAttribute:NSForegroundColorAttributeName value:C51 range:NSMakeRange(0,attrString.length)];
//    [attrString addAttribute:NSFontAttributeName value:font(14) range:NSMakeRange(0,attrString.length)];
    self.contentLb.attributedText = attrString;
    
    self.playTitleLb.text = model.title;

    if (model.status == XHPlayerNormal ||
        model.status == XHPlayerFinish ||
        model.status == XHPlayerFailed) {
        self.progressView.hidden = YES;
        self.playIcon.highlighted = NO;
        [self.progressView changePlayProgress:0 totalLength:model.totalTime];
    }else if (model.status == XHPlayerPause){
        self.playIcon.highlighted = NO;
        self.progressView.hidden = NO;
    }else{
        self.playIcon.highlighted = YES;
        self.progressView.hidden = self.model.progress == 0;
        [self.progressView changePlayProgress:model.currentTime totalLength:model.totalTime];
    }
    if (model.voiceUrl.length == 0 && model.id == nil) {
        [self.containView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView).offset(0);
            make.height.mas_equalTo(0).priorityHigh();
        }];
    }else{
        [self.containView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView).offset(32);
            make.height.mas_equalTo(80).priorityHigh();
        }];
    }
    
    if (model.title.length == 0) {
        [self.contentLb mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.containView.mas_bottom).offset(0);
        }];
    }else{
        [self.contentLb mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.containView.mas_bottom).offset(32);
        }];
    }
    self.model.isLoading = self.model.progress == 0;
    
    if (self.model.isLoading && self.model.status == XHPlayerPlay) {
        [self startAnimation];
    }else{
        [self stopAnimation];
    }
    
}
- (void)updateProgressValue{
    
    if (self.model.status == XHPlayerNormal ||
        self.model.status == XHPlayerFailed ||
        self.model.status == XHPlayerFinish) {
        self.progressView.hidden = YES;
        self.playIcon.highlighted = NO;
        [self.progressView changePlayProgress:0 totalLength:self.model.totalTime];
    }else if (self.model.status == XHPlayerPause){
        self.playIcon.highlighted = NO;
        self.progressView.hidden = NO;
        [self.progressView changePlayProgress:self.model.currentTime totalLength:self.model.totalTime];
    }else{
        self.playIcon.highlighted = YES;
        self.progressView.hidden = NO;
        [self.progressView changePlayProgress:self.model.currentTime totalLength:self.model.totalTime];
    }
    self.model.isLoading = self.model.progress == 0;
    
    if (self.model.isLoading && self.model.status == XHPlayerPlay) {
        [self startAnimation];
    }else{
        [self stopAnimation];
    }
    
}

@end
